<?php
namespace common\components;
/**
 * 图像处理
 */
class Ximage {
	public $w_pct = 100;
	public $w_jpgquality = 90;
	public $w_pngquality = 2;
	public $w_minwidth = 200;
	public $w_minheight = 200;
	public $thumb_enable;
	public $watermark_enable;
	public $interlace = 0;
	public $siteinfo = array();

    public function __construct() {

    }

	
	public function set_jpguqality($w_quality = 90){
		$this->w_jpgquality = $w_quality;
	}

	
	public function set_pnguqality($w_quality = 90){
		$this->w_pngquality = $w_quality;
	}

    public function info($img) {
        $imageinfo = getimagesize($img);
        if($imageinfo === false) return false;
		$imagetype = $imageinfo[2];
		$imagesize = filesize($img);
		$info = array(
				'width'=>$imageinfo[0],
				'height'=>$imageinfo[1],
				'type'=>$imagetype,
				'size'=>$imagesize,
				'mime'=>$imageinfo['mime'],
				
				);
		return $info;
    }
    
    public function getpercent($srcwidth,$srcheight,$dstw,$dsth) {
    	if (empty($srcwidth) || empty($srcheight) || ($srcwidth <= $dstw && $srcheight <= $dsth)) $w = $srcwidth ;$h = $srcheight;
    	if ((empty($dstw) || $dstw == 0)  && $dsth > 0 && $srcheight > $dsth) {
			$h = $dsth;
			$w = round($dsth / $srcheight * $srcwidth);
		} elseif ((empty($dsth) || $dsth == 0) && $dstw > 0 && $srcwidth > $dstw) {
			$w = $dstw;
			$h = round($dstw / $srcwidth * $srcheight);
		} elseif ($dstw > 0 && $dsth > 0) {
			if (($srcwidth / $dstw) < ($srcheight / $dsth)) {
					$w = round($dsth / $srcheight * $srcwidth);
					$h = $dsth;
			} elseif (($srcwidth / $dstw) > ($srcheight / $dsth)) {
					$w = $dstw;
					$h = round($dstw / $srcwidth * $srcheight );
			} else {
				$h = $dstw;
				$w = $dsth;
			}
		}
		$array['w']  = $w;
		$array['h']  = $h;
		return $array;
    }
    public function thumb($image, $filename = '', $maxwidth = 200, $maxheight = 200, $suffix='', $autocut = 0) {
		if(!$this->check($image)) return false;
        $info  = $this->info($image);
        if($info === false) return false;
		$srcwidth  = $info['width'];
		$srcheight = $info['height'];
		$pathinfo = pathinfo($image);
        if ($srcwidth <= $maxwidth) return false;
		$type =  $info['type'];
        if ($type == 1){
			$type = 'gif';
		}else if ($type == 2){
			$type = 'jpg';
		}else if ($type == 3){
			$type = 'png';
			
		}
		//if(!$type) $type = $info['type'];
		//$type = strtolower($type);
		unset($info);

		$creat_arr = $this->getpercent($srcwidth,$srcheight,$maxwidth,$maxheight);
		$createwidth = $width = $creat_arr['w'];
		$createheight = $height = $creat_arr['h'];

		$psrc_x = $psrc_y = 0;
		if($autocut && $maxwidth > 0 && $maxheight > 0) {
			if($maxwidth/$maxheight<$srcwidth/$srcheight && $maxheight>=$height) {
				$width = $maxheight/$height*$width;
				$height = $maxheight;
			}elseif($maxwidth/$maxheight>$srcwidth/$srcheight && $maxwidth>=$width) {
				$height = $maxwidth/$width*$height;
				$width = $maxwidth;
			}
			$createwidth = $maxwidth;
			$createheight = $maxheight;
		}
		$createfun = 'imagecreatefrom'.($type=='jpg' ? 'jpeg' : $type);
		$srcimg = $createfun($image);
		if($type != 'gif' && function_exists('imagecreatetruecolor'))
			$thumbimg = imagecreatetruecolor($createwidth, $createheight); 
		else
			$thumbimg = imagecreate($width, $height); 

		if(function_exists('imagecopyresampled'))
			imagecopyresampled($thumbimg, $srcimg, 0, 0, $psrc_x, $psrc_y, $width, $height, $srcwidth, $srcheight); 
		else
			imagecopyresized($thumbimg, $srcimg, 0, 0, $psrc_x, $psrc_y, $width, $height,  $srcwidth, $srcheight); 
		if($type=='gif' || $type=='png') {
			$background_color  =  imagecolorallocate($thumbimg,  0, 255, 0);  //  指派一个绿色  
			imagecolortransparent($thumbimg, $background_color);  //  设置为透明色，若注释掉该行则输出绿色的图 
		}
		if($type=='jpg' || $type=='jpeg') imageinterlace($thumbimg, $this->interlace);
		$imagefun = 'image'.($type=='jpg' ? 'jpeg' : $type);
		if(empty($filename)) $filename  = substr($image, 0, strrpos($image, '.')).$suffix.'.'.$type;
		$imagefun($thumbimg, $filename, $type=='png' ? $this->w_pngquality : $this->w_jpgquality);
		imagedestroy($thumbimg);
		imagedestroy($srcimg);

		return $filename;
    }


	public function watermark($source, $target = '', $w_pos = '', $w_img = '', $w_text = '',$w_font = 8, $w_color = '#ff0000') {
		$w_pos = $w_pos ? $w_pos : $this->w_pos;
		$w_img = $w_img ? $w_img : $this->w_img;
		if(!$this->watermark_enable || !$this->check($source)) return false;
		if(!$target) $target = $source;
		$w_img = PHPCMS_PATH.$w_img;
		$source_info = getimagesize($source);
		$source_w    = $source_info[0];
		$source_h    = $source_info[1];		
		if($source_w < $this->w_minwidth || $source_h < $this->w_minheight) return false;
		switch($source_info[2]) {
			case 1 :
				$source_img = imagecreatefromgif($source);
				break;
			case 2 :
				$source_img = imagecreatefromjpeg($source);
				break;
			case 3 :
				$source_img = imagecreatefrompng($source);
				break;
			default :
				return false;
		}
		if(!empty($w_img) && file_exists($w_img)) {
			$ifwaterimage = 1;
			$water_info   = getimagesize($w_img);
			$width        = $water_info[0];
			$height       = $water_info[1];
			switch($water_info[2]) {
				case 1 :
					$water_img = imagecreatefromgif($w_img);
					break;
				case 2 :
					$water_img = imagecreatefromjpeg($w_img);
					break;
				case 3 :
					$water_img = imagecreatefrompng($w_img);
					break;
				default :
					return;
			}
		} else {		
			$ifwaterimage = 0;
			$temp = imagettfbbox(ceil($w_font*2.5), 0, PC_PATH.'libs/data/font/elephant.ttf', $w_text);
			$width = $temp[2] - $temp[6];
			$height = $temp[3] - $temp[7];
			unset($temp);
		}
		switch($w_pos) {
			case 1:
				$wx = 5;
				$wy = 5;
				break;
			case 2:
				$wx = ($source_w - $width) / 2;
				$wy = 0;
				break;
			case 3:
				$wx = $source_w - $width;
				$wy = 0;
				break;
			case 4:
				$wx = 0;
				$wy = ($source_h - $height) / 2;
				break;
			case 5:
				$wx = ($source_w - $width) / 2;
				$wy = ($source_h - $height) / 2;
				break;
			case 6:
				$wx = $source_w - $width;
				$wy = ($source_h - $height) / 2;
				break;
			case 7:
				$wx = 0;
				$wy = $source_h - $height;
				break;
			case 8:
				$wx = ($source_w - $width) / 2;
				$wy = $source_h - $height;
				break;
			case 9:
				$wx = $source_w - $width;
				$wy = $source_h - $height;
				break;
			case 10:
				$wx = rand(0,($source_w - $width));
				$wy = rand(0,($source_h - $height));
				break;				
			default:
				$wx = rand(0,($source_w - $width));
				$wy = rand(0,($source_h - $height));
				break;
		}
		if($ifwaterimage) {
			if($water_info[2] == 3) {
				imagecopy($source_img, $water_img, $wx, $wy, 0, 0, $width, $height);
			} else {
				imagecopymerge($source_img, $water_img, $wx, $wy, 0, 0, $width, $height, $this->w_pct);
			}
		} else {
			if(!empty($w_color) && (strlen($w_color)==7)) {
				$r = hexdec(substr($w_color,1,2));
				$g = hexdec(substr($w_color,3,2));
				$b = hexdec(substr($w_color,5));
			} else {
				return;
			}
			imagestring($source_img,$w_font,$wx,$wy,$w_text,imagecolorallocate($source_img,$r,$g,$b));
		}
		
		switch($source_info[2]) {
			case 1 :
				imagegif($source_img, $target);
				break;
			case 2 :
				imagejpeg($source_img, $target, $this->w_quality);
				break;
			case 3 :
				imagepng($source_img, $target);
				break;
			default :
				return;
		}

		if(isset($water_info)) {
			unset($water_info);
		}
		if(isset($water_img)) {
			imagedestroy($water_img);
		}
		unset($source_info);
		imagedestroy($source_img);
		return true;
	}
	
	public function cut($src, $data){
		list($width, $height) = getimagesize($src);
		$info = $this->info($src);
		$viewPortW = $data["viewPortW"];
		$viewPortH = $data["viewPortH"];
		$pWidth = $data["imageW"];
		$pHeight =  $data["imageH"];
		$srcwidth  = $info['width'];
		$srcheight = $info['height'];
		$ext =  $info['type'];
        if ($ext == 1){
			$ext = 'gif';
		}else if ($ext == 2){
			$ext = 'jpg';
		}else if ($ext == 3){
			$ext = 'png';
			
		}
		$suffix = isset($data['suffix']) ? $data['suffix'] : '';
		$filename = isset($data['filename']) ? $data['filename'] : '';
		
		$function = $this->returnCorrectFunction($ext);
		$image = $function($src);
		$width = imagesx($image);
		$height = imagesy($image);
		// Resample
		$image_p = imagecreatetruecolor($pWidth, $pHeight);
		$this->setTransparency($image,$image_p,$ext);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $pWidth, $pHeight, $width, $height);
		imagedestroy($image);
		$widthR = imagesx($image_p);
		$hegihtR = imagesy($image_p);
		
		$selectorX = $data["selectorX"];
		$selectorY = $data["selectorY"];
		
		if($data["imageRotate"]){
			$angle = 360 - $data["imageRotate"];
			$image_p = imagerotate($image_p,$angle,0);
			
			$pWidth = imagesx($image_p);
			$pHeight = imagesy($image_p);
			
			//print $pWidth."---".$pHeight;
		
			$diffW = abs($pWidth - $widthR) / 2;
			$diffH = abs($pHeight - $hegihtR) / 2;
				
			$data["imageX"] = ($pWidth > $widthR ? $data["imageX"] - $diffW : $data["imageX"] + $diffW);
			$data["imageY"] = ($pHeight > $hegihtR ? $data["imageY"] - $diffH : $data["imageY"] + $diffH);
		
			
		}
		
		
		
		$dst_x = $src_x = $dst_y = $src_y = 0;
		
		if($data["imageX"] > 0){
			$dst_x = abs($data["imageX"]);
		}else{
			$src_x = abs($data["imageX"]);
		}
		if($data["imageY"] > 0){
			$dst_y = abs($data["imageY"]);
		}else{
			$src_y = abs($data["imageY"]);
		}
		
		
		$viewport = imagecreatetruecolor($data["viewPortW"],$data["viewPortH"]);
		$this->setTransparency($image_p,$viewport,$ext);
		
		imagecopy($viewport, $image_p, $dst_x, $dst_y, $src_x, $src_y, $pWidth, $pHeight);
		imagedestroy($image_p);
		
		
		$selector = imagecreatetruecolor($data["selectorW"],$data["selectorH"]);
		$this->setTransparency($viewport,$selector,$ext);
		imagecopy($selector, $viewport, 0, 0, $selectorX, $selectorY,$data["viewPortW"],$data["viewPortH"]);
		
		if(empty($filename)) $filename  = substr($src, 0, strrpos($src, '.')).$suffix.'.'.$ext;
		$this->parseImage($ext,$selector,$filename);
		imagedestroy($viewport);
		return $filename;
	}

	public function determineImageScale($sourceWidth, $sourceHeight, $targetWidth, $targetHeight) {
		$scalex =  $targetWidth / $sourceWidth;
		$scaley =  $targetHeight / $sourceHeight;
		return min($scalex, $scaley);
	}
	
	public function returnCorrectFunction($ext){
		$function = "";
		switch($ext){
			case "png":
				$function = "imagecreatefrompng";
				break;
			case "jpeg":
				$function = "imagecreatefromjpeg";
				break;
			case "jpg":
				$function = "imagecreatefromjpeg";
				break;
			case "gif":
				$function = "imagecreatefromgif";
				break;
		}
		return $function;
	}
	
	public function parseImage($ext,$img,$file = null){
		switch($ext){
			case "png":
				imagepng($img,($file != null ? $file : ''));
				break;
			case "jpeg":
				imagejpeg($img,($file ? $file : ''),90);
				break;
			case "jpg":
				imagejpeg($img,($file ? $file : ''),90);
				break;
			case "gif":
				imagegif($img,($file ? $file : ''));
				break;
		}
	}
	
	public function setTransparency($imgSrc,$imgDest,$ext){
	
		if($ext == "png" || $ext == "gif"){
			$trnprt_indx = imagecolortransparent($imgSrc);
			// If we have a specific transparent color
			if ($trnprt_indx >= 0) {
				// Get the original image's transparent color's RGB values
				$trnprt_color    = imagecolorsforindex($imgSrc, $trnprt_indx);
				// Allocate the same color in the new image resource
				$trnprt_indx    = imagecolorallocate($imgDest, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
				// Completely fill the background of the new image with allocated color.
				imagefill($imgDest, 0, 0, $trnprt_indx);
				// Set the background color for new image to transparent
				imagecolortransparent($imgDest, $trnprt_indx);
			}
			// Always make a transparent background color for PNGs that don't have one allocated already
			elseif ($ext == "png") {
				// Turn off transparency blending (temporarily)
				imagealphablending($imgDest, true);
				// Create a new transparent color for image
				$color = imagecolorallocatealpha($imgDest, 0, 0, 0, 127);
				// Completely fill the background of the new image with allocated color.
				imagefill($imgDest, 0, 0, $color);
				// Restore transparency blending
				imagesavealpha($imgDest, true);
			}
	
		}
	}
	public function check($image) {
		return extension_loaded('gd') && preg_match("/\.(jpg|jpeg|gif|png)/i", $image, $m) && file_exists($image) && function_exists('imagecreatefrom'.($m[1] == 'jpg' ? 'jpeg' : $m[1]));
	}
	
}
?>